/* Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.yzbdl.lanius.orchestrate.serv.dataBase;

import cn.hutool.db.ds.simple.SimpleDataSource;
import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yzbdl.lanius.orchestrate.common.base.dto.DataBaseInfo;

import java.util.Objects;

/**
 * 动态数据库
 *
 * @author zhuhongji
 * @date 2022-04-13 16:22
 */
public class DynamicDataBase {

	private static final Logger logger  =  LoggerFactory.getLogger(DynamicDataBase.class);


	/**
	 * 通过Druid获取数据库连接对象
	 * @return 数据库连接对象
	 */
	public static DruidDataSource getDruidDataSource(DataBaseInfo dataBaseInfo){
		DruidDataSource ds = new DruidDataSource();
		ds.setUrl(dataBaseInfo.getUrl());
		ds.setUsername(dataBaseInfo.getUserName());
		ds.setPassword(dataBaseInfo.getPassword());
		// 失败重试机制
		ds.setConnectionErrorRetryAttempts(3);
		// 请求失败后中断
		ds.setBreakAfterAcquireFailure(true);
		// 最长等待时间
		ds.setMaxWait(5000);
		return ds;
	}

	/**
	 * 测试数据库连通性；超时时间为10s
	 * @param url url
	 * @param username 用户名
	 * @param password 密码
	 * @return 成功与否
	 */
	public static Boolean testConnection(String url, String username, String password){
		SimpleDataSource simpleDataSource = null;
		try {
			if(!url.contains("connectTimeout")){
				String prefix = url.contains("?") ? "&" : "?" ;
				url = url + prefix + "connectTimeout=5000";
			}
			simpleDataSource = new SimpleDataSource(url, username, password);
			return simpleDataSource.getConnection().isValid(5);
		} catch (Exception e) {
			logger.error("数据库{}连接超时！", url, e);
			return false;
		} finally {
			try{
				if(Objects.nonNull(simpleDataSource)){
					simpleDataSource.close();
				}
			}
			catch (Exception e){
				logger.error("数据库{}关闭超时！", url, e);
			}
		}
	}

}
